﻿using System;
using System.Threading;
using System.Threading.Tasks;
using BookSleeve;
using RedisDemos.Extensions;

namespace RedisDemos.Scenarios
{
    public class CustomIncrement : Scenario
    {
        protected override async Task Perform(RedisConnection conn)
        {
            //SET key value
            await conn.Strings.Set(Db, "users:nextid", 5);

            ManualIncrement(conn, "1", 1000);
            ManualIncrement(conn, "2");

            await Task.Delay(2000);
        }

        private void ManualIncrement(RedisConnection conn, String name, Int32 sleepInSecs = 0)
        {
            Task.Factory.StartNew(async () =>
            {
                var result = false;

                // GET key
                var value = (await conn.Strings.Get(Db, "users:nextid")).AsInt64();

                // MULTI
                using (var tran = conn.CreateTransaction())
                {
                    // WATCH key [key ...] 
                    var wathTask = tran.AddCondition(Condition.KeyEquals(Db, "users:nextid", value));

                    Thread.Sleep(sleepInSecs); //simulate long running operation
                    var incremented = value + 1;

                    // SET key value
                    var setTask = tran.Strings.Set(Db, "users:nextid", incremented);

                    // EXEC
                    result = await tran.Execute();
                }

                // GET key
                value = (await conn.Strings.Get(Db, "users:nextid")).AsInt64();
                "{0} - {1}Incremented: {2}".LogInfo(name, result ? String.Empty : "Not ", value);
            }, TaskCreationOptions.LongRunning);
        }
    }
}
